package com.hdoit.ares.web.wechat.handler;

import java.util.Map;

import javax.annotation.Resource;

import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import org.springframework.stereotype.Component;

import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.enums.cust.AttentionStatus;
import com.tennetcn.common.logical.wechat.model.WechatOperateLog;
import com.tennetcn.common.logical.wechat.service.IWechatOperateLogService;
import com.tennetcn.common.selfcommon.enums.wechat.WechatOperateType;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.web.cbase.wechat.handler.BaseUnsubscribeHandler;

/**
 * 
 * @author Binary Wang
 *
 */
@Component
public class UnsubscribeHandler extends BaseUnsubscribeHandler {
	
	private ICustomerService customerService;
	
	public ICustomerService getCustomerService() {
		return customerService;
	}

	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	private IWechatOperateLogService wechatOperateLogService;
	
	public IWechatOperateLogService getWechatOperateLogService() {
		return wechatOperateLogService;
	}

	@Resource
	public void setWechatOperateLogService(IWechatOperateLogService wechatOperateLogService) {
		this.wechatOperateLogService = wechatOperateLogService;
	}

	@Override
	protected WxMpXmlOutMessage beforeHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
		String openId=wxMessage.getFromUser();
		Customer customer=customerService.queryModelByOpenId(openId);
		if(customer!=null){
			customer.setCancelAttentionDate(DateUtils.getCurrent());
			customer.setAttentionStatus(AttentionStatus.cancelAttention);
			customerService.updateModel(customer);
			
			saveWechatOperateLog(customer);
		}
		return null;
	}

	@Override
	protected WxMpXmlOutMessage afterHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
		return null;
	}
	
	private boolean saveWechatOperateLog(Customer customer){
		WechatOperateLog wechatOperateLog=new WechatOperateLog();
		wechatOperateLog.setId(CommonUtils.getKeyId());
		wechatOperateLog.setOpenId(customer.getOpenId());
		wechatOperateLog.setOperateDate(DateUtils.getCurrent());
		wechatOperateLog.setUserId(customer.getId());
		wechatOperateLog.setUsername(customer.getUsername());
		wechatOperateLog.setOperateType(WechatOperateType.cancelAttention);
		
		return wechatOperateLogService.addModel(wechatOperateLog);
	}

}
